#!/bin/bash
# Squid 代理一键安装脚本（兼容 Squid 3.5 版本）
# 支持 CentOS 7，修复时间单位和 IP 段格式问题

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

# 检查 root 权限
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}错误：请使用 root 用户运行此脚本！${NC}"
    exit 1
fi

# 定义参数（适配 Squid 3.5）
PROXY_PORT="3128"
ALLOW_IP="all"  # Squid 3.5 推荐用 all 代替 0.0.0.0/0
CONFIG_FILE="/etc/squid/squid.conf"
LOG_FILE="/var/log/squid_install.log"
SQUID_USER=""
SQUID_BIN=""

# 日志函数
log() {
    echo -e "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a "$LOG_FILE"
}

# 显示错误并退出
error_exit() {
    log "${RED}$1${NC}"
    exit 1
}

# 检测 Squid 命令路径
detect_squid_bin() {
    log "${YELLOW}检测 Squid 命令路径...${NC}"
    if command -v squid >/dev/null 2>&1; then
        SQUID_BIN=$(command -v squid)
        log "${GREEN}找到 Squid 命令：${SQUID_BIN}${NC}"
    else
        if [ -f "/usr/sbin/squid" ]; then
            SQUID_BIN="/usr/sbin/squid"
            log "${YELLOW}Squid 命令路径：${SQUID_BIN}${NC}"
        else
            error_exit "未找到 Squid 命令，请检查安装"
        fi
    fi
}

# 检查系统版本
check_os() {
    log "${YELLOW}检查系统版本...${NC}"
    if grep -q "CentOS Linux 7" /etc/redhat-release; then
        OS_VERSION="7"
        log "${GREEN}检测到 CentOS 7${NC}"
    else
        error_exit "仅支持 CentOS 7 系统"
    fi
}

# 检测 Squid 运行用户
detect_squid_user() {
    log "${YELLOW}检测 Squid 运行用户...${NC}"
    if id squid &>/dev/null; then
        SQUID_USER="squid"
    elif id proxy &>/dev/null; then
        SQUID_USER="proxy"
    else
        log "${YELLOW}创建 Squid 用户...${NC}"
        useradd -r -s /sbin/nologin squid
        SQUID_USER="squid"
    fi
    log "${GREEN}Squid 用户：${SQUID_USER}${NC}"
}

# 安装 Squid
install_squid() {
    log "${YELLOW}安装 Squid...${NC}"
    yum install -y squid || error_exit "yum 安装 Squid 失败"
    
    # 验证安装
    detect_squid_bin
    
    # 检查版本（适配 3.5 版本）
    SQUID_VERSION=$($SQUID_BIN -v 2>&1 | grep "Version" | awk '{print $4}')
    if [ -z "$SQUID_VERSION" ]; then
        error_exit "无法获取 Squid 版本"
    fi
    log "${GREEN}Squid 版本：${SQUID_VERSION}${NC}"
}

# 配置 Squid（适配 3.5 版本）
configure_squid() {
    log "${YELLOW}配置 Squid...${NC}"
    
    TEMP_CONFIG="/tmp/squid_temp.conf"
    
    # 生成兼容 Squid 3.5 的配置（时间单位用秒，IP 段用 all）
    cat > "$TEMP_CONFIG" <<EOF
# Squid 3.5 兼容配置
http_port ${PROXY_PORT}

# 访问控制（用 all 代替 0.0.0.0/0）
acl allowed_ip src ${ALLOW_IP}
http_access allow allowed_ip
http_access deny all

# 日志配置
access_log /var/log/squid/access.log
cache_log /var/log/squid/cache.log

# 禁用缓存
cache deny all

# 超时设置（Squid 3.5 只支持秒为单位）
client_body_timeout 60  # 1分钟 = 60秒
connect_timeout 60
request_timeout 60

# 支持 HTTPS 代理
acl SSL_ports port 443
acl CONNECT method CONNECT
http_access allow CONNECT SSL_ports
EOF
    
    log "${YELLOW}生成的配置文件内容：${NC}"
    cat "$TEMP_CONFIG" | tee -a "$LOG_FILE"
    
    # 验证配置
    log "${YELLOW}验证配置文件...${NC}"
    $SQUID_BIN -k parse -f "$TEMP_CONFIG" >/dev/null 2>&1
    
    if [ $? -ne 0 ]; then
        log "${RED}配置文件错误！${NC}"
        CONFIG_ERROR=$($SQUID_BIN -k parse -f "$TEMP_CONFIG" 2>&1)
        log "${RED}错误详情：${CONFIG_ERROR}${NC}"
        error_exit "配置文件生成失败"
    fi
    
    # 备份并应用配置
    [ -f "$CONFIG_FILE" ] && mv "$CONFIG_FILE" "${CONFIG_FILE}.bak"
    mv "$TEMP_CONFIG" "$CONFIG_FILE"
    chown ${SQUID_USER}:${SQUID_USER} "$CONFIG_FILE"
    
    # 日志目录权限
    mkdir -p /var/log/squid
    chown -R ${SQUID_USER}:${SQUID_USER} /var/log/squid
    
    log "${GREEN}Squid 配置完成${NC}"
}

# 配置防火墙
configure_firewall() {
    log "${YELLOW}开放 ${PROXY_PORT} 端口...${NC}"
    if systemctl is-active --quiet firewalld; then
        firewall-cmd --add-port="${PROXY_PORT}/tcp" --permanent >/dev/null 2>&1
        firewall-cmd --reload >/dev/null 2>&1
        log "${GREEN}firewalld 配置完成${NC}"
    else
        iptables -I INPUT -p tcp --dport ${PROXY_PORT} -j ACCEPT
        service iptables save >/dev/null 2>&1
        log "${GREEN}iptables 配置完成${NC}"
    fi
}

# 启动 Squid
start_squid() {
    log "${YELLOW}启动 Squid 服务...${NC}"
    systemctl start squid
    sleep 2
    
    if systemctl is-active --quiet squid; then
        log "${GREEN}Squid 服务启动成功！${NC}"
        log "${GREEN}\n===== 代理信息 ====="
        log "服务器地址：$(hostname -I | awk '{print $1}')"
        log "代理端口：${PROXY_PORT}"
        log "类型：HTTP/HTTPS"
        log "管理命令：systemctl [start|stop|restart] squid"
        log "====================${NC}"
    else
        log "${RED}启动失败！错误日志：${NC}"
        journalctl -u squid -n 10 --no-pager | tee -a "$LOG_FILE"
        error_exit "Squid 启动失败"
    fi
}

# 主流程
main() {
    > "$LOG_FILE"
    log "${GREEN}===== Squid 一键安装开始 ====${NC}"
    
    check_os
    detect_squid_user
    install_squid
    configure_squid
    configure_firewall
    start_squid
    
    log "${GREEN}===== 安装完成 ====${NC}"
}

main